package com.yiyun.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.yiyun.blog.dao.pojo.SysUser;
import com.yiyun.blog.service.TokenService;
import com.yiyun.blog.utils.JWTUtils;
import com.yiyun.blog.vo.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author Bao
 * @create 2022-03-04-17:08
 */
@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //检查token是否合法，并返回用户信息
    @Override
    public SysUser checkToken(String token) {

        //检查token是否为空
        if (StringUtils.isBlank(token)){
            return null;
        }
        //检查token是否合法
        Map<String, Object> stringObjectMap = JWTUtils.checkToken(token);
        if (stringObjectMap == null){

            return null;
        }
        //检查token是否过期；获取用户信息
         String userJson = redisTemplate.opsForValue().get("Token" + token);
        if (StringUtils.isBlank(userJson)){
            return null;
        }
        //将userJson转换成SysUser类型
        SysUser sysUser = JSON.parseObject(userJson,SysUser.class);
        return sysUser;
    }
}
